package com.magictower.primary.activity;

import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.format.Formatter;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.magictower.primary.R;
import com.magictower.primary.adapter.TaskManagerAdapter;
import com.magictower.primary.bean.TaskInfo;
import com.magictower.primary.common.SPConstant;
import com.magictower.primary.engine.TaskInfoParser;
import com.magictower.primary.service.KillProcessWidgetService;
import com.magictower.primary.utils.SystemInfoUtils;
import com.magictower.primary.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author kejunzhan
 * @since 2017/12/21
 */

public class TaskManagerActivity extends AppCompatActivity {
    @ViewInject(R.id.list_view)
    private ListView list_view;
    @ViewInject(R.id.tv_task_process_count)
    private TextView tv_task_process_count;
    @ViewInject(R.id.tv_task_memory)
    private TextView tv_task_memory;
    private List<TaskInfo> userTaskInfos;
    private List<TaskInfo> systemTaskInfos;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            tv_task_process_count.setText("进程:" + taskCount + "个");
            tv_task_process_count.setSingleLine();
            long availMem = SystemInfoUtils.getAvailMem(TaskManagerActivity.this);
            long totalMem = SystemInfoUtils.getTotalMem(TaskManagerActivity.this);
            tv_task_memory.setText("剩余/总内存:" + Formatter.formatFileSize(TaskManagerActivity.this, availMem)
                    + "/" + Formatter.formatFileSize(TaskManagerActivity.this, totalMem) + "");
            tv_task_memory.setSingleLine();
            adapter = new TaskManagerAdapter(TaskManagerActivity.this,
                    userTaskInfos, systemTaskInfos);
            list_view.setAdapter(adapter);
        }
    };
    private int taskCount;
    private TaskManagerAdapter adapter;
    private SharedPreferences mPref;
    private ActivityManager am;
    private Intent intent;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task_manager);
        ViewUtils.inject(this);
        mPref = getSharedPreferences(SPConstant.CONFIG, MODE_PRIVATE);
        am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);

        initUI();
        initData();

        boolean isShow = mPref.getBoolean(SPConstant.CLENA_PROCESS, false);
        if (isShow) {
            //启动清理控件
            intent = new Intent(this, KillProcessWidgetService.class);
            startService(intent);
        }
    }

    private void initUI() {
        list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TaskInfo item = (TaskInfo) adapter.getItem(position);
                if (item == null) {
                    //如果点击是灰色标题，则为空
                    return;
                }
                if (item.isChecked()) {
                    item.setChecked(false);
                } else {
                    item.setChecked(true);
                }
                adapter.notifyDataSetChanged();
            }
        });
    }

    private void initData() {
        new Thread() {
            @Override
            public void run() {
                userTaskInfos = new ArrayList<>();
                systemTaskInfos = new ArrayList<>();
                List<TaskInfo> taskInfos = TaskInfoParser.getTaskInfos(TaskManagerActivity.this);
                taskCount = taskInfos.size();
                for (TaskInfo taskInfo : taskInfos) {
                    if (taskInfo.isUserApp()) {
                        userTaskInfos.add(taskInfo);
                    } else {
                        systemTaskInfos.add(taskInfo);
                    }
                }
                handler.sendEmptyMessage(0);
            }
        }.start();
    }

    public void selectAll(View view) {
        for (TaskInfo taskInfo : userTaskInfos) {
            if (taskInfo.getPackageName().equals(getPackageName())) {
                //自己的进程，不操作
            } else {
                taskInfo.setChecked(true);
            }
        }
        for (TaskInfo taskInfo : systemTaskInfos) {
            taskInfo.setChecked(true);
        }
        adapter.notifyDataSetChanged();
    }

    public void selectOpposite(View view) {
        for (TaskInfo taskInfo : userTaskInfos) {
            if (taskInfo.getPackageName().equals(getPackageName())) {
                //自己的进程，不操作
            } else {
                if (taskInfo.isChecked()) {
                    taskInfo.setChecked(false);
                } else {
                    taskInfo.setChecked(true);
                }
            }
        }
        for (TaskInfo taskInfo : systemTaskInfos) {
            if (taskInfo.isChecked()) {
                taskInfo.setChecked(false);
            } else {
                taskInfo.setChecked(true);
            }
        }
        adapter.notifyDataSetChanged();
    }

    public void killProcess(View view) {
        int size = 0;
        List<TaskInfo> killTask = new ArrayList<>();
        for (TaskInfo taskInfo : userTaskInfos) {
            if (taskInfo.isChecked()) {
                //选中，删除
                size++;
                //后台杀死进程
                am.killBackgroundProcesses(taskInfo.getPackageName());
                killTask.add(taskInfo);
            }
        }
        for (TaskInfo taskInfo : systemTaskInfos) {
            if (taskInfo.isChecked()) {
                //选中，删除
                size++;
                am.killBackgroundProcesses(taskInfo.getPackageName());
                killTask.add(taskInfo);
            }
        }
        //更新list列表数据
        for (TaskInfo taskInfo : killTask) {
            if (taskInfo.isUserApp()) {
                userTaskInfos.remove(taskInfo);
            } else {
                systemTaskInfos.remove(taskInfo);
            }
        }
        taskCount = userTaskInfos.size() + systemTaskInfos.size();

        ToastUtils.showToast(this, "已消除 " + size + " 个应用");
        handler.obtainMessage();
        handler.sendEmptyMessage(0);
    }

    public void openSetting(View view) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("设置显示");
        boolean show1 = mPref.getBoolean(SPConstant.SHOW_SYSTEM_PROCESS, false);
        boolean show2 = mPref.getBoolean(SPConstant.CLENA_PROCESS, false);
        CharSequence[] charSequences = new CharSequence[]{"显示系统应用", "启动清理控件"};
        final boolean[] booleen = new boolean[]{show1, show2};
        builder.setMultiChoiceItems(charSequences, booleen, new DialogInterface.OnMultiChoiceClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which, boolean isChecked) {

            }
        });
        builder.setNegativeButton("取消", null);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Editor editor = mPref.edit();
                editor.putBoolean(SPConstant.SHOW_SYSTEM_PROCESS, booleen[0]);
                editor.putBoolean(SPConstant.CLENA_PROCESS, booleen[1]);
                editor.apply();
                dialog.dismiss();
                handler.obtainMessage();
                handler.sendEmptyMessage(0);
            }
        });
        builder.show();
    }

    @Override
    protected void onStart() {
        super.onStart();
        System.out.println("TaskManagerActivity: " + SystemInfoUtils.isServiceRunning(TaskManagerActivity.this,
                "KillProcessWidgetService"));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (intent != null) {
            stopService(intent);
        }
    }
}
